package base.thread_demo.demo11;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * ReentrantLock..tryLock() 可被打断的锁对象，可被打断是说在阻塞队列中可被打断
 */
public class ReentrantLockDemo04 {
    private static final Logger log = LoggerFactory.getLogger(ReentrantLockDemo04.class);

    public static void main(String[] args) throws Exception {
        ReentrantLock lock = new ReentrantLock();

        Thread t1 = new Thread(()->{
            try {
                log.info("t1 start...");
                if(!lock.tryLock(3, TimeUnit.SECONDS)) {
                    log.info("t1 持续了3s都获取不到锁");
                    return;
                }
            } catch (InterruptedException e) {
                log.info("t1 在持续获取锁的过程中被打断");
                return;
            }

            try {
                while(true) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        log.info(e.toString());
                       // break;// 如果在sleep过程中被打断,就结束线程任务,退出循环
                    }
                    log.info("t1 获取到锁，执行锁定任务逻辑");
                }
            } finally {
                log.info("t1 释放锁");
                lock.unlock();
            }
        },"t1");

        lock.lock();
        log.info("main 获得锁");
        t1.start();
        Thread.sleep(2000);
        log.info("main 释放锁");
        lock.unlock();
        Thread.sleep(2000);
        log.info("main 企图打断t1");
        t1.interrupt();
    }
}
